package com.xuebank.nfe.nfecar.fragment

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.os.Build
import android.os.Bundle
import android.os.Message
import android.support.annotation.RequiresApi
import android.support.v4.content.ContextCompat
import android.util.Log
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.webkit.*
import android.widget.LinearLayout
import com.wzn.libaray.event.RxBus
import com.wzn.libaray.utils.Logger
import com.wzn.libaray.utils.cache.SharedPreferencesUtil
import com.xuebank.nfe.nfecar.MainActivity
import com.xuebank.nfe.nfecar.R
import com.xuebank.nfe.nfecar.activity.SecondActivity
import com.xuebank.nfe.nfecar.beas.BaseFragment
import com.xuebank.nfe.nfecar.globals.Constants
import com.xuebank.nfe.nfecar.model.RefreshHtml
import com.xuebank.nfe.nfecar.utils.NfeConstants
import com.xuebank.nfe.nfecar.utils.XueBankUtils
import com.xuebank.nfe.nfecar.utils.bridge.BridgeWebView
import com.xuebank.nfe.nfecar.utils.bridge.BridgeWebViewClient
import com.xuebank.nfe.nfecar.utils.statusbar.StatusBarUtil
import org.json.JSONObject
@RequiresApi(Build.VERSION_CODES.M)
class HomeFragment : BaseFragment() {


    private var mWebView: BridgeWebView? = null
    private var webSettings: WebSettings? = null
    private var newWebView: BridgeWebView? = null
    private val APP_CACAHE_DIRNAME = "/webcache"
    private var llWebView:LinearLayout? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        StatusBarUtil.setColor(activity, ContextCompat.getColor(activity!!, R.color.white))
        StatusBarUtil.setTranslucent(activity)
        return inflater.inflate(R.layout.fragment_home, container, false)

    }


    override fun initData(savedInstanceState: Bundle?) {
    }

    override fun findViews() {
        mWebView = findViewById(R.id.home_bridgeWebView)
        llWebView = findViewById(R.id.home_ll)
    }
    override fun initViews() {

        initWebView()

        RxBus.getDefault().toObserverable(RefreshHtml::class.java)
                .compose(this.bindUntilEvent(com.trello.rxlifecycle.android.FragmentEvent.DESTROY))
                .subscribe({ reques ->
                    try {
                        val refreshHtml = RefreshHtml()
                        val isRefresh =refreshHtml.refresh
                        val jsonObject = JSONObject()
                        val flag = if (isRefresh == true) "1" else "0"
                        jsonObject.put("isRefresh", flag)
                        //                    webViewSendRequest("");
                        val json = JSONObject()
                        json.put("action", "StartRefresh")
                        json.put("data", jsonObject)
                        mWebView?.callHandler("XueBankWebViewNativeBridge", json.toString(), null)
                        mWebView?.loadUrl(Constants.HOME_URL)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                })
    }

    @SuppressLint("SetJavaScriptEnabled")
    private fun initWebView() {
        webSettings = mWebView?.settings
        webSettings?.setJavaScriptEnabled(true)
        val userAgentString = webSettings?.userAgentString
        webSettings?.userAgentString = userAgentString + ";IcarRefit"
        webSettings?.allowFileAccess = true
        webSettings?.setSupportZoom(false)
        webSettings?.allowContentAccess = true
        webSettings?.useWideViewPort = true
        webSettings?.domStorageEnabled = true
        webSettings?.loadWithOverviewMode = true
        webSettings?.loadsImagesAutomatically = true
        webSettings?.cacheMode = WebSettings.LOAD_DEFAULT
        val defaultUserAgent = webSettings?.userAgentString
        //webSettings.setUserAgentString(Constants.WebViewUA + " " + ICBCUtil.getVerName() + " fullversion:" + ICBCUtil.getFullVerCode() + " " + defaultUserAgent);
        if (Build.VERSION.SDK_INT >= 11)
            mWebView?.settings?.allowContentAccess = true
        if (Build.VERSION.SDK_INT >= 21)
            mWebView?.settings?.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW

        if (webSettings != null) {
            setWebViewCacheMode(webSettings!!)
        }

    }


    @SuppressLint("ClickableViewAccessibility")
    fun setWebViewCacheMode(webViewCacheMode: WebSettings) {
        webSettings?.setRenderPriority(WebSettings.RenderPriority.HIGH)
        webSettings?.javaScriptCanOpenWindowsAutomatically = true
        // 支持多窗口
        webSettings?.setSupportMultipleWindows(true)
        // 开启 DOM storage API 功能
        webSettings?.setDomStorageEnabled(true)
        // 开启 Application Caches 功能
        webSettings?.setAppCacheEnabled(true)
        val cacheDirPath = context.filesDir.absolutePath + APP_CACAHE_DIRNAME
        //设置数据库缓存路径
        webSettings?.setDatabasePath(cacheDirPath)
        //设置  Application Caches 缓存目录
        webSettings?.setAppCachePath(cacheDirPath)
        webSettings?.databaseEnabled = true
        //通过xml资源文件获得animation实例
        //        iv_background.setImageResource(R.drawable.anim_xb);
        //        xbAnimation = (AnimationDrawable) iv_background.getDrawable();
        mWebView?.webChromeClient = object : WebChromeClient() {

            override fun onCreateWindow(view: WebView, isDialog: Boolean, isUserGesture: Boolean, resultMsg: Message): Boolean {
                newWebView = BridgeWebView(context)
                newWebView?.webViewClient = object : WebViewClient() {
                    override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                        val intent = Intent(activity, SecondActivity::class.java)
                        intent.putExtra("url", url)
                        startActivityForResult(intent, NfeConstants.REFRESH_REQUEST)
                        return true
                    }
                }
                //                initWebView(newWebView);//初始化webview
                llWebView?.addView(newWebView)
                val transport = resultMsg.obj as WebView.WebViewTransport//以下的操作应该就是让新的webview去加载对应的url等操作。
                transport.webView = newWebView
                resultMsg.sendToTarget()
                return true
            }

            override fun onJsAlert(view: WebView, url: String, message: String, result: JsResult): Boolean {
                result.confirm()
                return true
            }

            override fun onExceededDatabaseQuota(url: String, databaseIdentifier: String, quota: Long, estimatedDatabaseSize: Long, totalQuota: Long, quotaUpdater: WebStorage.QuotaUpdater) {
                //设置数据库存储大小
                quotaUpdater.updateQuota(estimatedDatabaseSize * 2)
            }

        }
        mWebView?.webViewClient = object : BridgeWebViewClient(mWebView) {
            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                Log.e(TAG, "onPageStarted")
                super.onPageStarted(view, url, favicon)
            }
            override fun onPageFinished(view: WebView?, url: String?) {



                mWebView?.setOnLongClickListener(View.OnLongClickListener { true })

                Log.e(TAG, "onPageFinished")
                requestData()
                val cookieManager = CookieManager.getInstance()
                cookieManager.setAcceptCookie(true)
                val CookieStr = cookieManager.getCookie(url)
//                Logger.d("首页的cookie", CookieStr)
                if (CookieStr != null) {
                    SharedPreferencesUtil.getInstance(context).applyString(MainActivity.COOKIE,CookieStr)
                    Logger.d("首页的cookie", CookieStr)
                }
                super.onPageFinished(view, url)

            }


            override fun onLoadResource(view: WebView?, url: String?) {
                Log.e(TAG, url)
                super.onLoadResource(view, url)
            }

            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                Log.e(TAG, url)
                return super.shouldOverrideUrlLoading(view, url)
            }



            override  fun onReceivedError(view: WebView?, request: WebResourceRequest?, error: WebResourceError?) {
                super.onReceivedError(view, request, error)
            }
        }
        mWebView?.setOnTouchListener(View.OnTouchListener { v, event ->
            mWebView?.getParent()?.requestDisallowInterceptTouchEvent(true)
            val x = event.rawX.toInt()
            val y = event.rawY.toInt()
            var lastX = 0
            var lastY = 0
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    lastX = x
                    lastY = y
                }
                MotionEvent.ACTION_MOVE -> {
                    val deltaY = y - lastY
                    val deltaX = x - lastX
                    if (Math.abs(deltaX) < Math.abs(deltaY)) {
                        mWebView?.getParent()?.requestDisallowInterceptTouchEvent(true)
                    } else {
                        mWebView?.getParent()?.requestDisallowInterceptTouchEvent(true)
                    }
                }
                else -> {
                }
            }
            false
        })
//        if (SharedPreferencesUtil.getInstance(context).getString(MainActivity.COOKIE) != null) {
//            MainActivity.synchronousWebCookies(context,Constants.MINE_URL)
//            mWebView?.loadUrl(Constants.HOME_URL)
//        } else {
            mWebView?.loadUrl(Constants.HOME_URL)
//        }


    }


    @RequiresApi(Build.VERSION_CODES.M)
    private fun requestData() {
        mWebView?.registerHandler("XueBankWebViewJavascriptBridge") { data, function ->
            Log.e("BridgeHandler", data)
            var jsonObject: JSONObject? = null
            try {
                val xbutils = XueBankUtils(activity)
                jsonObject = JSONObject(data)
                val send_action = jsonObject.getString("action")
                xbutils.doBridgeHandler(data, object : XueBankUtils.callBack {
                    override fun onCallBack(result: String) {
                        Log.e("onCallBack", result)
                        function.onCallBack(result)
                    }
                })

            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

}// Required empty public constructor
